package com.serverapk;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.bumptech.glide.Glide;
import com.danikula.videocache.HttpProxyCacheServer;
import com.serverapk.ad.PlayerVideoView;
import com.serverapk.ad.TopView;
import com.serverapk.adapter.ViewAdapter1;
import com.serverapk.camera.CameraService;
import com.serverapk.camera.ImgChange;
import com.serverapk.camera.ImgDeal;
import com.serverapk.eth.EthSetting;
import com.serverapk.interfaces.MediaStreamListener;
import com.serverapk.model.CachedThreadFactory;
import com.serverapk.model.CardData;
import com.serverapk.model.DeleteData;
import com.serverapk.model.ListData;
import com.serverapk.model.Notify;
import com.serverapk.model.ShangPinData;
import com.serverapk.model.UpGradeData;
import com.serverapk.model.Video;
import com.serverapk.model.VideoData;
import com.serverapk.para.Common;
import com.serverapk.reader.HcReaderUtil;
import com.serverapk.receiver.NetStateBroadReceiver;
import com.serverapk.services.MyMqttService;
import com.serverapk.services.OssService;
import com.serverapk.socket.SocketUtil;
import com.serverapk.upgrade.UpGradeUtils;
import com.serverapk.util.FileUtil;
import com.serverapk.util.GpioUtil;
import com.serverapk.util.H264Saver;
import com.serverapk.util.L;
import com.serverapk.util.ListUtils;
import com.serverapk.util.PermissionUtils;
import com.serverapk.util.PrintToFileUtil;
import com.serverapk.util.QRCodeUtil;
import com.serverapk.util.RootUtil;
import com.serverapk.util.SPUtils;
import com.serverapk.util.ShellUtils;
import com.serverapk.util.ToastUtil;
import com.serverapk.util.Util;


import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import com.vveye.rtsprecord.VVCameraSDK;

import vv.jnilib.camlib;


public class MainActivity extends Activity {
    private String TAG = "MainActivity";
    private Context context;
    private CameraService cameraService = new CameraService();
    private ImgDeal imgDeal = new ImgDeal();
    private boolean getGpioState = true;
    private boolean initParaFlag = true;
    private boolean getNetworkFlag = true;
    private PlayerVideoView playerVideoView;
    //    private ImgRollView imgRollView;
    private boolean isStop = false;//线程是否停止

    private Handler handler = new Handler();

    private UsbDevice usbDevice = null;
    private String Device_USB = "com.android.example.USB";
    private byte[] snr = new byte[4];

    private final int CODE = 200;
    private final int INSTALL_APK_REQUESTCODE = 10010;

    /**
     * 表示的dmcode扇区的密码
     */
//    private String dmcodePsd = "862899987320";
    private String dmcodePsd = "099470087337";
    /**
     * 表示的stpcode扇区的密码
     */
    private String stpcodePsd;
    /**
     * 表示存储扇区密码的IC卡扇区的代码，默认是2
     */
    private String dmcode = "1";
    /**
     * 表示的是存放卡号，金额的扇区
     */
    private String stpcode;

    /**
     * 0表示请求dmcode扇区的密码 1表示请求stpcode扇区的密码
     */
    private int flag = 0;

    /**
     * 卡片的唯一序列号
     */
    private String id;

    private CardData cardData;

    //http://dmg.nex-i.cn/gbox?device=869012040631439

    private MediaPlayer mediaPlayer;

    private ImageView iv1;
    private ImageView iv_pic;
    //    private ImageView iv2;
    private Bitmap bitmap;
    private Bitmap bitmap1;

    private ViewPager viewPager;
    private List<View> viewList;
    private ViewAdapter1 adapter;

    private int currentPosition = 0;
    int totalSize;

    private NetStateBroadReceiver receiver;

    private final String SID = "OHAYkLo3LJcqQmq65co5owmbCNipBrIg";
    private ArrayList<Video> videoArrayList;

    private int currentVideoPosition = 0;//当前播放的视频或图片position
    private int totalCount;//视频或图片列表size

    //动态视频
    private VVCameraSDK vvCameraSDK;
    private int frameCount1 = 0;//开始后摄像1的返回帧数
    private int frameCount2 = 0;//开始后摄像1的返回帧数
    private H264Saver h264Saver1;
    private H264Saver h264Saver2;
    private String current2;
    private String current1;

    //阿里云上传服务
    private OssService ossService;

    private List<String> listFile;

    private boolean isFirstLoad = true;

    private String seq;

    //    private TencentLocationManager tencentLocationManager;
    private String lon;
    private String lat;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        setContentView(R.layout.activity_main);
        hideStatusBar();
        context = this;
        EventBus.getDefault().register(this);
        maxVolume();

        //发现对于Android 6.0以上系统，不能只是在AndroidManifest.xml中进行配置，
        // 还要在程序代码中进行动态设置相应的权限。
        requestPermission();

//        if (RootUtil.isDeviceRooted()) {
//            L.e("设备具有root权限");
//        } else {
//            L.e("设备不具有root权限！！！！");
//        }

    }

    //全屏并且隐藏状态栏
    private void hideStatusBar() {
        WindowManager.LayoutParams attrs = getWindow().getAttributes();
        attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setAttributes(attrs);
    }

    private void judgeNetwork() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                while (getNetworkFlag) {
                    if (TopView.networkFlag) {
                        if (TopView.signal > 0) {
                            initData();
                        } else {
//                            Toast.makeText(context, "没有网络", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    } else {
                        try {
                            Thread.sleep(1000 * 5);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();
    }

    private void init_socket() {
        for (int i = 0; i < Common.cameraIp.size(); i++) {
            Common.socketMap.put(i, new SocketUtil(Common.cameraIp.get(i), Common.cameraPort));
        }
    }

    private void init_file() {
        File file = new File(Common.filepath);
        if (!file.exists()) {
            file.mkdirs();
        }
        File file2 = new File(Common.filepath_bak);
        if (!file2.exists()) {
            file2.mkdirs();
        }
        File file3 = new File(Common.crash_path);
        if (!file3.exists()) {
            file3.mkdirs();
        }
    }

    public void init_gpio() {
        GpioUtil.gpio_output_high(Common.test_gpio1);
        GpioUtil.gpio_input(Common.check_gpio1);
        GpioUtil.gpio_input(Common.check_gpio2);
    }

    public void init_broad() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.setPriority(1000);
        intentFilter.addAction("com.lockstate");
        registerReceiver(mReceiver, intentFilter);
    }

    public void init() {
        playerVideoView = (PlayerVideoView) findViewById(R.id.playerVideoView);
        iv_pic = (ImageView) findViewById(R.id.iv_pic);

        iv1 = (ImageView) findViewById(R.id.iv1);
        viewPager = (ViewPager) findViewById(R.id.viewPager);

    }

    public void autoPlayAudioView() {
//        playerVideoView.palyer(Common.ad_path);
//        playerVideoView.setAutoPlayer();
//        playerVideoView.getClick();
    }

    public void wait_for_gpio() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (getGpioState) {
                    try {
                        Thread.sleep(1000);
                        Log.d(TAG, "[TONY] wait for 1s...");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    if (GpioUtil.checkGpioExists(Common.check_gpio1) && GpioUtil.checkGpioExists(Common.check_gpio2)) {
                        Intent intent = new Intent("com.lockstate");
                        intent.putExtra(Common.check_gpio1, GpioUtil.checkGpioStatus(Common.check_gpio1));
                        intent.putExtra(Common.check_gpio2, GpioUtil.checkGpioStatus(Common.check_gpio2));
                        sendBroadcast(intent);
                    }
                }
            }
        }).start();
    }

    BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            int a = intent.getIntExtra(Common.check_gpio1, -1);
            final int b = intent.getIntExtra(Common.check_gpio2, -1);

            if ((a == Common.close_lock_state && b == Common.close_lock_state)) {//落锁
                if (Common.last_check_gpio1 != a || Common.last_check_gpio2 != b) {
                    if (isFirstLoad) {
                        isFirstLoad = false;
                    } else {

                        seq = Common.seq;
                        //停止录像
                        if (BaseApplication.getInstance().isVideo && vvCameraSDK != null) {
                            try {
                                handler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        BaseApplication.getInstance().isNotifySuc = false;
                                        isFirst = true;
                                        vvCameraSDK.stop();
//                                        vvCameraSDK = null;
                                        //获取数据停止后统一转换成MP4保存
                                        if (h264Saver1 != null) {
//                                        PrintToFileUtil.input2File("存视频-" + current1, PrintToFileUtil.PATH);
                                            h264Saver1.close();
                                            h264Saver1.newH264ToMp4(Common.video_path + "/" + current1 + ".mp4", Common.video_path + "/" + current1 + ".264");

                                            upload1(seq);
                                        }
                                        if (h264Saver2 != null) {
                                            h264Saver2.close();
                                            h264Saver2.newH264ToMp4(Common.video_path + "/" + current2 + ".mp4", Common.video_path + "/" + current2 + ".264");
                                            upload2(seq);
                                        }
                                    }
                                }, 1000);
                                BaseApplication.getInstance().isNotifySuc = true;
                            } catch (Exception e) {
                                L.e("关门报错：" + e.toString());
                            }

                        }
                        if (Common.type == 1) {
                            ImgChange.delFiles(Common.filepath);
                            cameraService.getPicture(Common.socketMap, new MediaStreamListener() {

                                @Override
                                public void onFinish(String ret) {
                                    L.e("main识别结果：" + ret);
                                    // 获取图片成功
                                    imgDeal.getImgList();
                                }

                                @Override
                                public void onError(int code, String e) {
                                    // 获取图片异常
                                    L.e(TAG, e);
                                    PostNex.errorPost(code, e);
                                }
                            });
                        }

                        try {
                            if (mediaPlayer == null) {
                                mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.close);
                            }
                            mediaPlayer.start();

                            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                                @Override
                                public void onCompletion(MediaPlayer mp) {
                                    stopPlay();
                                }
                            });
                        } catch (Exception e) {
                            stopPlay();
                        }
                    }
                    PostNex.statusPost(a, b);
                    Common.last_check_gpio1 = a;
                    Common.last_check_gpio2 = b;

                }
            } else if (a == Common.open_lock_state && b == Common.open_lock_state) {
                if (Common.last_check_gpio1 != a || Common.last_check_gpio2 != b) {
                    PostNex.statusPost(a, b);
                    Common.last_check_gpio1 = a;
                    Common.last_check_gpio2 = b;
                }
            } else if (a == Common.close_lock_state && b == Common.open_lock_state) {
                if (Common.last_check_gpio1 != a || Common.last_check_gpio2 != b) {
                    PostNex.statusPost(a, b);
                    Common.last_check_gpio1 = a;
                    Common.last_check_gpio2 = b;
                }

            } else if (a == Common.open_lock_state && b == Common.close_lock_state) {
                if (Common.last_check_gpio2 == a && Common.last_check_gpio2 != b) { //关门
                    GpioUtil.gpio_output(Common.test_gpio1, Common.close_lock);
                }
                if (Common.last_check_gpio1 != a || Common.last_check_gpio2 != b) {
                    PostNex.statusPost(a, b);
                    Common.last_check_gpio1 = a;
                    Common.last_check_gpio2 = b;
                }

            }
        }
    };

    public void stopPlay() {
        if (mediaPlayer != null) {
            try {
                mediaPlayer.stop();
            } catch (Exception e) {
                e.printStackTrace();
                mediaPlayer = null;
                mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.close);
                mediaPlayer.stop();
            }
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    PostNex postNex;

    @TargetApi(26)
    public void initData() {
        try {

//            Common.imei = Util.getIMEI(context);
//            Common.imei = "869012040730751";//动态柜
//            Common.imei = "869012040628062";//869012040633484 353254060402068

            Common.imei = Util.getIMEI(context);

            if (Common.imei != null && !"".equals(Common.imei)) {
                L.e("imei===" + Common.imei);
                PostNex.initPost(lon, lat);
                PostNex.getList(SID, Common.imei);
                PostNex.getVideo(SID, Common.imei);

                handler.post(new Runnable() {
                    @Override
                    public void run() {
//                        bitmap = QRCodeUtil.createQRCode("http://dmg.nex-i.cn/gbox?device=" + Common.imei, 400);
                        bitmap = QRCodeUtil.createQRCode("http://dmg.nex-i.cn/mp/qr?id=" + Common.imei, 400);
                        iv1.setImageBitmap(bitmap);
                    }
                });

            } else {//如果没有获取到imei    十秒后再进行获取
                try {
                    Thread.sleep(1000 * 10);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                Common.imei = Util.getIMEI(context);
                PostNex.initPost(lon, lat);
            }
        } catch (Exception e) {
            L.e("e;" + e.toString());
        }

    }

    private void pingIpAddr() {
        CachedThreadFactory.getInstance().addTask("ping" + System.currentTimeMillis(), new Runnable() {
            @Override
            public void run() {
                boolean pingResult = true;
                try {
                    for (int i = 0; i < Common.cameraIp.size(); i++) {
                        Process process = Runtime.getRuntime().exec("/system/bin/ping -c 1 -w 10 " + Common.cameraIp.get(i));
                        int status = process.waitFor();
                        L.e("@@@@@@@@@@@@@@@@@@@@@@@@@status=" + status);
                        if (status != 0) {
                            pingResult = false;
                            PostNex.errorPost(Common.error_code5, Common.error_info5 + "-" + Common.cameraIp.get(i));
                            break;
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                EventBus.getDefault().post(pingResult);
            }
        });

    }

    private MyMqttService mqttService;
    private ServiceConnection mqttConn = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub
            mqttBindFlag = true;
            mqttService = ((MyMqttService.LocalBinder) service).getService();
            mqttService.start(context);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mqttService.stop();
            mqttService = null;
        }

    };

    boolean mqttBindFlag = false;

    private void doBindService() {
        bindService(new Intent(this, MyMqttService.class), mqttConn, Context.BIND_AUTO_CREATE);
    }

    private void doUnbindService() {
        if (mqttBindFlag) {
            unbindService(mqttConn);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
        }

        EventBus.getDefault().unregister(this);
        CachedThreadFactory.getInstance().clearAllTask();
        //关闭读写器
        if (BaseApplication.getInstance().reader != null)
            BaseApplication.getInstance().reader.hc_exit();

        unregisterReceiver(mReceiver);
        unregisterReceiver(TopView.networkChangeReceiver);
        getGpioState = false;
        initParaFlag = false;
        getNetworkFlag = false;
        isStop = true;
        isFirstLoad = true;
        PostNex.heartFlag = false;
        doUnbindService();
//        unRegisterBroad();
    }

    /* 创建广播接收器 **/
    private BroadcastReceiver mUsbBroadcast = new BroadcastReceiver() {
        public void onReceive(Context paramAnonymousContext, Intent paramAnonymousIntent) {
            Log.w(TAG, "进入广播接收器1");
            String action = paramAnonymousIntent.getAction();
            // 判断广播类型
            if (Device_USB.equals(action)) {
                try {
                    // 如果用户同意，则对读写器进行操作
                    if (paramAnonymousIntent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        short st = BaseApplication.getInstance().reader.OpenReader(usbDevice);
                        if (st >= 0) {
                            L.e(TAG, "读写器连接成功!");
                        } else {
                            L.e(TAG, "读写器连接失败!");
                        }
                    } else {
                        Toast.makeText(MainActivity.this, "操作被拒绝.", Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();

        IntentFilter filter = new IntentFilter(Device_USB);
        /*
         * 在使用USB读写器设备前，应用必须获得权限。
		 * 为了确切地获得权限，首先需要创建一个广播接收器。在调用requestPermission()这个方法时从得到的广播中监听这个意图。
		 * 通过调用requestPermission()这个方法为用户跳出一个是否连接该设备的对话框。
		 */
        this.registerReceiver(this.mUsbBroadcast, filter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 销毁在onResume()方法中的广播
        unregisterReceiver(mUsbBroadcast);
    }

    private void upload1(final String seq) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (ossService == null)
                    ossService = new OssService(MainActivity.this, Common.accessKey, Common.secretKey, Common.endPoint, Common.bucketName, Common.cameraIp.size());
                ossService.beginupload(MainActivity.this, current1 + ".mp4", Common.video_path + "/" + current1 + ".mp4", 1, seq);
            }
        }, 1000);
    }

    private void upload2(final String seq) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (ossService == null)
                    ossService = new OssService(MainActivity.this, Common.accessKey, Common.secretKey, Common.endPoint, Common.bucketName, Common.cameraIp.size());
                ossService.beginupload(MainActivity.this, current2 + ".mp4", Common.video_path + "/" + current2 + ".mp4", 2, seq);

            }
        }, 6000);
    }

    /**
     * 动态权限申请，针对6.0以上版本
     */
    private void requestPermission() {
        if (!PermissionUtils.checkPermission(this, new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE}, 200)) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_PHONE_STATE},
                    CODE);
            //安卓 8.0要动态申请安装权限
            if (Build.VERSION.SDK_INT >= 26) {
                //来判断应用是否有权限安装apk
                boolean installAllowed = getPackageManager().canRequestPackageInstalls();
                if (!installAllowed) {
                    //无权限 申请权限
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES}, INSTALL_APK_REQUESTCODE);
                }
            }
        } else {
            init();
            judgeNetwork();
            init_file();

            init_gpio();
            init_broad();
            wait_for_gpio();

            autoPlayAudioView();
            creatVideoPath();

            listFile = FileUtil.GetFiles(Common.base_path, "apk", true);
            for (final String str : listFile) {
                CachedThreadFactory.getInstance().addTask(str, new Runnable() {
                    @Override
                    public void run() {
                        FileUtil.deleteFile(new File(str));
                        CachedThreadFactory.getInstance().removeTask(str);
                    }
                });
            }

            if (FileUtil.getFileOrFilesSize(Common.video_path, FileUtil.SIZETYPE_MB) >= FileUtil.MAX_MEMORY) {
                CachedThreadFactory.getInstance().addTask(System.currentTimeMillis() + "", new Runnable() {
                    @Override
                    public void run() {
                        FileUtil.deleteFile(new File(Common.video_path));
                    }
                });

            }
            if (FileUtil.getFileOrFilesSize(Common.crash_path, FileUtil.SIZETYPE_MB) >= 20) {
                CachedThreadFactory.getInstance().addTask(System.currentTimeMillis() + "", new Runnable() {
                    @Override
                    public void run() {
                        FileUtil.deleteFile(new File(Common.crash_path));
                    }
                });

            }

            mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.close);

//            tencentLocationManager = TencentLocationManager.getInstance(this);
//            tencentLocationManager.requestSingleFreshLocation(null, this, Looper.getMainLooper());
        }
    }

    /**
     * 创建视频存储文件夹
     */
    private void creatVideoPath() {
        File file = new File(Common.video_path);
        if (!file.exists()) {//如果文件夹不存在
            file.mkdir();//创建文件夹
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (permissions.length > 0 && requestCode == CODE) {
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    ToastUtil.showLong(MainActivity.this, "请授予权限，以保证软件正常运行");
                    requestPermission();
                    return;
                }
            }
            init();
            judgeNetwork();
            init_file();

            init_gpio();
            init_broad();
            wait_for_gpio();

            autoPlayAudioView();
            creatVideoPath();


            listFile = FileUtil.GetFiles(Common.base_path, "apk", true);
            for (final String str : listFile) {
                CachedThreadFactory.getInstance().addTask(str, new Runnable() {
                    @Override
                    public void run() {
                        FileUtil.deleteFile(new File(str));
                        CachedThreadFactory.getInstance().removeTask(str);
                    }
                });
            }

            if (FileUtil.getFileOrFilesSize(Common.video_path, FileUtil.SIZETYPE_MB) >= FileUtil.MAX_MEMORY) {
                CachedThreadFactory.getInstance().addTask(System.currentTimeMillis() + "", new Runnable() {
                    @Override
                    public void run() {
                        FileUtil.deleteFile(new File(Common.video_path));
                    }
                });
            }
            if (FileUtil.getFileOrFilesSize(Common.crash_path, FileUtil.SIZETYPE_MB) >= 20) {
                CachedThreadFactory.getInstance().addTask(System.currentTimeMillis() + "", new Runnable() {
                    @Override
                    public void run() {
                        FileUtil.deleteFile(new File(Common.crash_path));
                    }
                });

            }

            mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.close);

//            tencentLocationManager = TencentLocationManager.getInstance(this);
//            tencentLocationManager.requestSingleFreshLocation(null, this, Looper.getMainLooper());
        }

        switch (requestCode) {
            case INSTALL_APK_REQUESTCODE:
                //有注册权限且用户允许安装
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                } else {
                    //将用户引导至安装未知应用界面。
                    Uri packageURI = Uri.parse("package:" + getPackageName());//设置包名，可直接跳转当前软件的设置页面
                    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
                break;
        }

    }

    private void handlerUnUploadVideo() {
//        boolean isUploadSuc = (boolean) SPUtils.get(MainActivity.this, "isUploadSuc", true);
//        if (!isUploadSuc) {
//            if (Common.cameraIp.size() == 1) {
//                upload1(isUploadSuc, "");
//            } else if (Common.cameraIp.size() == 2) {
//                upload1(isUploadSuc, "");
//                upload2(isUploadSuc, "");
//            }
//        }
    }


    private String file1;//第一个摄像头视频名称
    private String file2;//第二个摄像头视频名称
    private boolean isSuc1;
    private boolean isSuc2;
    private volatile int position = 0;

    //定义处理接收的方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getEventBusMsg(Object object) {
        try {
            if (object instanceof UpGradeData) {
                UpGradeData upGradeData = (UpGradeData) object;
                String url = upGradeData.getUrl();
                L.e("升级地址=" + url);

                UpGradeUtils.getInstance().download(url, UpGradeUtils.getInstance().path, onDownloadListener);
            } else if (object instanceof ListData) {
                ListData listData = (ListData) object;
                int code = listData.getCode();
                if (code == 10000) {
                    ArrayList<ShangPinData> list = null;
                    list = listData.getData();

                    if (list != null && list.size() > 0) {
                        viewPager.setVisibility(View.VISIBLE);
                        viewList = new ArrayList<>();
                        viewList.clear();
                        addView(list);

                        adapter = new ViewAdapter1(viewList);
                        viewPager.setAdapter(adapter);
                        totalSize = viewList.size();
                        viewPager.setCurrentItem(currentPosition);
//                        timer.schedule(task, 5000, 5000);

                        handler.postDelayed(runnable1, 5000);

                    }
                }
            } else if (object instanceof VideoData) {
                VideoData videoData = (VideoData) object;
                int code = videoData.getCode();
                if (code == 10000) {
                    videoArrayList = videoData.getData();
                    totalCount = videoArrayList.size();
                    play();
                }

            } else if (object instanceof String) {
                String str = (String) object;
                if (str.equals(Common.refresh)) {
                    L.e("refresh====");
                    currentPosition = 0;
                    handler.removeCallbacks(runnable1);
                    PostNex.getList(SID, Common.imei);
                } else if (str.equals("reboot")) {

                } else if (str.equals(Common.open_door)) {
                    L.e("开门===");
                    if (Common.type == 2) {//动态视觉识别柜
                        if (BaseApplication.getInstance().isVideo) {
                            L.e("动态开门=====");
                            //把当前时间作为视频文件名
//                        long current = System.currentTimeMillis();
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
                            Date date = new Date(System.currentTimeMillis());
                            String current = simpleDateFormat.format(date);
                            current1 = current + "-" + Common.imei + "--1";
                            current2 = current + "-" + Common.imei + "--2";


                            if (Common.dev_id.length() > 0) {
                                try {
//                                    if (vvCameraSDK != null) {
//                                        vvCameraSDK.stop();
//                                        vvCameraSDK = null;
//                                    }
                                    if (vvCameraSDK == null) {
                                        vvCameraSDK = VVCameraSDK.getInstance();
                                        vvCameraSDK.init(this, Common.dev_id, new VVCameraSDK.OnSDKStateChangedCallback() {
                                            @Override
                                            public void initSuccess() {
//                                            PrintToFileUtil.input2File("初始化成功--" + current1, PrintToFileUtil.PATH);
                                                L.e("初始化成功==========");
                                                //初始化成功
                                                //开始获取摄像头数据
                                                frameCount1 = 0;
                                                frameCount2 = 0;
                                                h264Saver1 = null;
                                                h264Saver2 = null;
                                                vvCameraSDK.start(onCameraDataCallback);
                                            }

                                            @Override
                                            public void initFailure(String s) {
                                                //初始化失败
                                                L.e("initFailure " + s);
                                                PostNex.errorPost(Common.error_code10, Common.error_info10 + ":initFailure=" + s);
                                            }

                                            @Override
                                            public void onFailure(String s) {
                                                //使用中出错
                                                L.e("onFailure" + s);
                                                PostNex.errorPost(Common.error_code10, Common.error_info10 + ":onFailure=" + s);
                                            }
                                        });
                                    } else {
                                        frameCount1 = 0;
                                        frameCount2 = 0;
                                        h264Saver1 = null;
                                        h264Saver2 = null;
                                        vvCameraSDK.start(onCameraDataCallback);
                                    }
                                } catch (Exception e) {
                                    L.e("初始化视频报错：" + e.toString());
                                }

                            }
                        }
                    }
                } else if (str.equals("ping")) {
                    doBindService();
                    init_socket();
                    PostNex.initFlag = false;
//                    dealPing();
                    pingIpAddr();

//                    handlerUnUploadVideo();

                } else if (str.equals("reupload")) {
//                    handler.postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            handlerUnUploadVideo();
//                        }
//                    }, 1000);
                }
            } else if (object instanceof Notify) {
                ++position;

                Notify notify = (Notify) object;
                String index = notify.getIndex();

                if (index.equals("1")) {
                    file1 = notify.getName();
                    isSuc1 = notify.isSuc();
                } else if (index.equals("2")) {
                    file2 = notify.getName();
                    isSuc2 = notify.isSuc();
                }

                if (position == 2) {
//                    PostNex.notifyPost(null, file1 + "," + file2);
                    PostNex.notifyPostVideo(null, file1 + "," + file2, seq);

                    if (isSuc1 && isSuc2) {
                        L.e("上传成功，notify----");
//                        if (!(boolean) SPUtils.get(context, "isUploadSuc", true)) {
//                            SPUtils.put(context, "isUploadSuc", true);
//                        }
                        //只有一个摄像头 上传视频成功后 就删除你本地视频

                        final String name_264 = file1.split("\\.")[0] + ".264";
                        final String name_264_2 = file2.split("\\.")[0] + ".264";

                        //上传成功 删除本地保存的视频
                        CachedThreadFactory.getInstance().addTask(file1, new Runnable() {
                            @Override
                            public void run() {
                                CachedThreadFactory.getInstance().removeTask(file1);

                                File file = new File(Common.video_path + "/" + file1);
                                FileUtil.deleteFile(file);
                                File file_264 = new File(Common.video_path + "/" + name_264);
                                FileUtil.deleteFile(file_264);

                            }
                        });

                        //上传成功 删除本地保存的视频
                        CachedThreadFactory.getInstance().addTask(file2, new Runnable() {
                            @Override
                            public void run() {
                                CachedThreadFactory.getInstance().removeTask(file2);

                                File file_2 = new File(Common.video_path + "/" + file2);
                                FileUtil.deleteFile(file_2);
                                File file_264_2 = new File(Common.video_path + "/" + name_264_2);
                                FileUtil.deleteFile(file_264_2);

                            }
                        });


                    } else {
//                        EventBus.getDefault().post("reupload");
                    }

                    if (FileUtil.getFileOrFilesSize(Common.video_path, FileUtil.SIZETYPE_MB) >= FileUtil.MAX_MEMORY) {
                        CachedThreadFactory.getInstance().addTask(System.currentTimeMillis() + "", new Runnable() {
                            @Override
                            public void run() {
                                FileUtil.deleteFile(new File(Common.video_path));
                            }
                        });
                    }

                    file1 = "";
                    file2 = "";
                    isSuc1 = false;
                    isSuc2 = false;
                    position = 0;

//                    BaseApplication.getInstance().isNotifySuc = true;
                }


            } else if (object instanceof Boolean) {
                boolean isPingSuc = (boolean) object;
                if (isPingSuc) {
                    postNex = new PostNex(context);
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            postNex.heartPost();
                            handler.postDelayed(this, Common.heartTime * 1000);
                        }
                    });
                } else {
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            pingIpAddr();
                        }
                    }, 3000);
                }
            }

        } catch (Exception e) {
            L.e("getEventBusMsg error=" + e.toString());
        }
    }

    private Runnable runnable1 = new Runnable() {
        @Override
        public void run() {
            currentPosition++;
            currentPosition = getCurrentItem(currentPosition++, totalSize);
            viewPager.setCurrentItem(currentPosition);
            handler.postDelayed(runnable1, 5000);
        }
    };


    volatile boolean isFirst = true;
    /**
     * 获取摄像头帧数据回调
     */
    camlib.OnCameraDataCallback onCameraDataCallback = new camlib.OnCameraDataCallback() {
        /**
         * @param index
         *摄像头序号，192.168.9.81 对应 0  192.168.9.82对应1 以此类推
         * @param type
         * 240 = 主帧 241 = 辅帧
         * @param data
         * 帧数据
         * @param data_len
         * 帧数据长度
         */
        @Override
        public void dataCallback(int index, int type, byte[] data, int data_len) {
            //此处只展示获取camera ip为 192.168.9.81 index = 0 的摄像头数据，并且保存成MP4
            try {
                if (isFirst) {
                    isFirst = false;
//                    PrintToFileUtil.input2File("拿到摄像头数据-" + current1, PrintToFileUtil.PATH);
                }
                if (index == 0) {
//                    cameraCount = 1;
                    if (frameCount1 == 0) {
                        //第一帧，先创建文件,存储成264流文件
                        h264Saver1 = new H264Saver(Common.video_path + "/" + current1 + ".264", MainActivity.this);
                    }
                    //写入流数据
                    h264Saver1.writeData(data, data_len, type);
                    frameCount1++;
                } else if (index == 1) {
//                    cameraCount = 2;
                    if (frameCount2 == 0) {
                        //第一帧，先创建文件,存储成264流文件
                        h264Saver2 = new H264Saver(Common.video_path + "/" + current2 + ".264", MainActivity.this);
                    }
                    //写入流数据
                    h264Saver2.writeData(data, data_len, type);
                    frameCount2++;
                }
            } catch (Exception e) {
                L.e("dataCallback:" + e.toString());
            }
        }
    };


    private void play() {
        try {
            Video video1 = videoArrayList.get(currentVideoPosition);
            int duration = video1.getDuration() * 1000;
            int type = video1.getType();
            String url = video1.getUrl();
            if (type == 1) {
                iv_pic.setVisibility(View.VISIBLE);
                playerVideoView.setVisibility(View.GONE);
                Glide.with(MainActivity.this).load(url).into(iv_pic);
            } else if (type == 2) {
                iv_pic.setVisibility(View.GONE);
                playerVideoView.setVisibility(View.VISIBLE);
                initVideo(url);
            }
//            L.e("currentVideoPosition=" + currentVideoPosition);
            currentVideoPosition++;
            handler.postDelayed(runnable, duration);
        } catch (Exception e) {
            L.e("play error:" + e.toString());
        }

    }

    private void initVideo(String url) {
        HttpProxyCacheServer proxy = BaseApplication.getProxy(this);
        //1.我们会将原始url注册进去
        // proxy.registerCacheListener(, bean.getVideo_url());
        //2.我们播放视频的时候会调用以下代码生成proxyUrl
        String proxyUrl = proxy.getProxyUrl(url);
        if (proxy.isCached(url)) {
            L.e("已缓存");
        } else {
            L.e("未缓存");
        }
        L.e("aaaapath==" + proxyUrl);
        playerVideoView.setVideoPath(proxyUrl);
        playerVideoView.start();
        playerVideoView.findFocus();
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            currentVideoPosition = setCurrentPosition(currentVideoPosition, totalCount);
            play();
        }
    };

    private int setCurrentPosition(int current, int total) {
        int position = -1;
        if (current < total) {
            position = current;
        } else {
            position = 0;
        }
        return position;
    }

    private int getCurrentItem(int current, int total) {
        int position = -1;
//        if (current <= total) {
//            position = current;
//        } else {
//            position = current % (total + 1);
//        }
        if (current < total) {
            position = current;
        } else {
            position = 0;
        }
//        L.e("po=" + position);
        return position;
    }

    private void addView(ArrayList<ShangPinData> list) {
        int size = list.size();
        double d = size / 3.0;
        int viewPagerSize = (int) Math.ceil(d);
        List<List<ShangPinData>> sprateList = ListUtils.partition(list, 3);


        for (int x = 0; x < viewPagerSize; x++) {
            List<ShangPinData> dataList = sprateList.get(x);
            View view = LayoutInflater.from(this).inflate(R.layout.item_list, null);
            ImageView iv1 = view.findViewById(R.id.iv1);
            ImageView iv2 = view.findViewById(R.id.iv2);
            ImageView iv3 = view.findViewById(R.id.iv3);

            TextView tv_name1 = view.findViewById(R.id.tv_name1);
            TextView tv_name2 = view.findViewById(R.id.tv_name2);
            TextView tv_name3 = view.findViewById(R.id.tv_name3);

            TextView tv_price1 = view.findViewById(R.id.tv_price1);
            TextView tv_price2 = view.findViewById(R.id.tv_price2);
            TextView tv_price3 = view.findViewById(R.id.tv_price3);

            TextView tv_kucun1 = view.findViewById(R.id.tv_kucun1);
            TextView tv_kucun2 = view.findViewById(R.id.tv_kucun2);
            TextView tv_kucun3 = view.findViewById(R.id.tv_kucun3);


            try {
                Glide.with(MainActivity.this).load(dataList.get(0).getBanner()).into(iv1);
                tv_name1.setText(dataList.get(0).getName());
                tv_price1.setText("价格:" + dataList.get(0).getPrice() + "元/每件");
                tv_kucun1.setText("库存:" + dataList.get(0).getCount() + "件");
//                L.e("=" + dataList.get(0).getCount());
            } catch (Exception e) {
//                L.e("e1=" + e.toString());
            }

            try {
                Glide.with(MainActivity.this).load(dataList.get(1).getBanner()).into(iv2);
                tv_name2.setText(dataList.get(1).getName());
                tv_price2.setText("价格:" + dataList.get(1).getPrice() + "元/每件");
                tv_kucun2.setText("库存:" + dataList.get(1).getCount() + "件");
            } catch (Exception e) {
//                L.e("e2=" + e.toString());
            }
            try {
                Glide.with(MainActivity.this).load(dataList.get(2).getBanner()).into(iv3);
                tv_name3.setText(dataList.get(2).getName());
                tv_price3.setText("价格:" + dataList.get(2).getPrice() + "元/每件");
                tv_kucun3.setText("库存:" + dataList.get(2).getCount() + "件");
            } catch (Exception e) {
//                L.e("e3=" + e.toString());
            }
            viewList.add(view);

        }


    }

    private UpGradeUtils.OnDownloadListener onDownloadListener = new UpGradeUtils.OnDownloadListener() {
        @Override
        public void onDownloadSuccess(File file) {
            L.e("apk路径：" + file.getPath() + ",," + file.getAbsolutePath());

            Intent intent1 = new Intent(Intent.ACTION_MAIN);
            /**知道要跳转应用的包命与目标Activity*/
            ComponentName componentName = new ComponentName("com.example.installutils", "com.example.installutils.MainActivity");
            intent1.setComponent(componentName);
            intent1.putExtra("apkPath", file.getPath());//这里Intent传值
            L.e("apkpath=" + file.getPath());
            intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent1);

            System.exit(0);

        }

        @Override
        public void onDownloading(int progress) {
            L.e("下载进度：" + progress);
        }

        @Override
        public void onDownloadFailed() {
            L.e("下载失败：");
        }
    };

    private AudioManager audioMa;

    public void maxVolume() {//最大音量调整

        audioMa = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        int mSystemMax = audioMa.getStreamMaxVolume(AudioManager.STREAM_SYSTEM);

        audioMa.setStreamVolume(AudioManager.STREAM_SYSTEM, mSystemMax, 0);

        audioMa.setStreamVolume(AudioManager.STREAM_MUSIC, audioMa.getStreamMaxVolume

                (AudioManager.STREAM_MUSIC), AudioManager.FLAG_SHOW_UI);

        audioMa.setRingerMode(AudioManager.RINGER_MODE_NORMAL);

    }

//    @Override
//    public void onLocationChanged(TencentLocation tencentLocation, int i, String s) {
//        lon = tencentLocation.getLongitude() + "";
//        lat = tencentLocation.getLatitude() + "";
//
//        BaseApplication.getInstance().lon = lon;
//        BaseApplication.getInstance().lat = lat;
//
//        L.e("lon=" + lon + ",lat=" + lat);
//
//        new Thread(new Runnable() {
//
//            @Override
//            public void run() {
//                // TODO Auto-generated method stub
//                while (getNetworkFlag) {
//                    if (TopView.networkFlag) {
//                        if (TopView.signal > 0) {
//                            initData();
//                        } else {
//                        }
//                        break;
//                    } else {
//                        try {
//                            Thread.sleep(1000 * 5);
//                        } catch (InterruptedException e) {
//                            // TODO Auto-generated catch block
//                            e.printStackTrace();
//                        }
//                    }
//                }
//            }
//        }).start();
//    }
//
//    @Override
//    public void onStatusUpdate(String s, int i, String s1) {
//
//    }

}
